package com.nanjia.boot.stock.productbatch.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nanjia.boot.batch_stock.mapper.WarehouseBatchStockMapper;
import com.nanjia.boot.batch_stock.model.entity.WarehouseBatchStock;
import com.nanjia.boot.common.enums.StatusEnum;
import com.nanjia.boot.common.enums.StockStatus;
import com.nanjia.boot.common.result.Result;
import com.nanjia.boot.core.security.util.SecurityUtils;
import com.nanjia.boot.manufacturer.mapper.ManufacturerMapper;
import com.nanjia.boot.manufacturer.model.entity.Manufacturer;
import com.nanjia.boot.product.sku.mapper.ProductSkuMapper;
import com.nanjia.boot.product.sku.model.entity.ProductSku;
import com.nanjia.boot.stock.productbatch.converter.ProductBatchConverter;
import com.nanjia.boot.stock.productbatch.mapper.ProductBatchMapper;
import com.nanjia.boot.stock.productbatch.model.entity.ProductBatch;
import com.nanjia.boot.stock.productbatch.model.form.ProductBatchForm;
import com.nanjia.boot.stock.productbatch.model.query.ProductBatchQuery;
import com.nanjia.boot.stock.productbatch.model.vo.ProductBatchVO;
import com.nanjia.boot.stock.productbatch.service.ProductBatchService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产品批次主记录服务实现类
 *
 * @author 周洋
 * @since 2025-08-21 16:30
 */
@Service
@RequiredArgsConstructor
public class ProductBatchServiceImpl extends ServiceImpl<ProductBatchMapper, ProductBatch> implements ProductBatchService {

    private final ProductBatchConverter productBatchConverter;

    private final ProductBatchMapper productBatchMapper;

    private final ProductSkuMapper productSkuMapper;

    private final ManufacturerMapper manufacturerMapper;

    private final WarehouseBatchStockMapper warehouseBatchStockMapper;

    /**
     * 获取产品批次主记录分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<ProductBatchVO>} 产品批次主记录分页列表
     */
    @Override
    public IPage<ProductBatchVO> getProductBatchPage(ProductBatchQuery queryParams) {
        Page<ProductBatchVO> pageVO = this.baseMapper.getProductBatchPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }

    /**
     * 获取产品批次主记录表单数据
     *
     * @param id 产品批次主记录ID
     * @return 产品批次主记录表单数据
     */
    @Override
    public ProductBatchForm getProductBatchFormData(Long id) {
        ProductBatch entity = this.getById(id);
        return productBatchConverter.toForm(entity);
    }

    /**
     * 新增产品批次主记录
     *
     * @param formData 产品批次主记录表单对象
     * @param ipAddr
     * @return 是否新增成功
     */
    @Override
    public Result saveProductBatch(ProductBatchForm formData, String ipAddr) {

        if (formData == null
                || StringUtils.isEmpty(formData.getBatchNumber())
                || formData.getSkuId() == null
                || formData.getWarehouseId() == null
                || formData.getWarehouseStorageLocationId() == null
                || formData.getManufacturerId() == null) {
            return Result.failed("参数不全");
        }
        Manufacturer manufacturer = manufacturerMapper.selectById(formData.getManufacturerId());
        if (manufacturer == null) {
            return Result.failed("制造商不存在");
        }
        ProductSku productSku = productSkuMapper.selectById(formData.getSkuId());
        if (productSku == null) {
            return Result.failed("SKU不存在");
        } else if (productSku.getStatus().intValue() == StatusEnum.DELETE.getValue()) {
            return Result.failed("SKU不合法");
        }
        List<ProductBatch> list = this.list(new LambdaQueryWrapper<ProductBatch>().eq(ProductBatch::getBatchNumber, formData.getBatchNumber()).eq(ProductBatch::getSkuId, formData.getSkuId()));
        if (!list.isEmpty()) {
            return Result.failed("该SKU和批次号重复入库");
        }

        ProductBatch entity = productBatchConverter.toEntity(formData);
        entity.setCreateBy(SecurityUtils.getUserStrId());
        entity.setCreateIp(ipAddr);
        entity.setCreateTime(LocalDateTime.now());
        boolean save = this.save(entity);
        if (!save) {
            return Result.failed("保存失败");
        }
        WarehouseBatchStock warehouseBatchStock = new WarehouseBatchStock();

        warehouseBatchStock.setBatchId(entity.getId());
        warehouseBatchStock.setWarehouseId(formData.getWarehouseId());
        warehouseBatchStock.setQuantity(formData.getQuantityProduced());
        warehouseBatchStock.setStockStatus(StockStatus.WAITING.getStatus());
        warehouseBatchStock.setStorageLocationId(formData.getWarehouseStorageLocationId());
        warehouseBatchStock.setCreateBy(SecurityUtils.getUserStrId());
        warehouseBatchStock.setCreateIp(ipAddr);
        warehouseBatchStock.setCreateTime(LocalDateTime.now());
        int insert = warehouseBatchStockMapper.insert(warehouseBatchStock);
        if (insert != 1) {
            return Result.failed("新增产品批次失败");
        }
        return Result.success();
    }

    /**
     * 更新产品批次主记录
     *
     * @param id       产品批次主记录ID
     * @param formData 产品批次主记录表单对象
     * @param ipAddr
     * @return 是否修改成功
     */
    @Override
    public boolean updateProductBatch(Long id, ProductBatchForm formData, String ipAddr) {
        ProductBatch entity = productBatchConverter.toEntity(formData);
        entity.setId(id);
        entity.setUpdateBy(JSONUtil.toJsonStr(SecurityUtils.getUserId()));
        entity.setUpdateIp(ipAddr);
        entity.setUpdateTime(LocalDateTime.now());
        return this.updateById(entity);
    }

    /**
     * 删除产品批次主记录
     *
     * @param ids 产品批次主记录ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteProductBatchs(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的产品批次主记录数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Override
    public List<ProductBatchVO> getProductBatchOptions(ProductBatchQuery queryParams) {
        LambdaQueryWrapper<ProductBatch> queryWrapper = new LambdaQueryWrapper<>();
        if (queryParams != null) {
            if (queryParams.getManufacturerId() != null) {
                queryWrapper.eq(ProductBatch::getManufacturerId, queryParams.getManufacturerId());
            }
        }
        queryWrapper.orderByDesc(ProductBatch::getId);
        List<ProductBatch> list = this.list(queryWrapper);
        return list.stream().map(productBatchConverter::toVO).collect(Collectors.toList());
    }
}
